<template>
  <a-modal
    v-model:visible="modalVisible"
    @cancel="closeModal"
    width="600px"
    :top="100"
    :align-center="false"
    title="新增权限"
    @ok="handleSubmit"
  >
    <template #footer>
      <a-button @click="closeModal">取消</a-button>
      <a-button type="primary" @click="handleSubmit">确定</a-button>
    </template>
    <a-form :rules="rules" :model="form.list" ref="formRef">
      <a-form-item field="menuType" label="类型:">
        <a-select v-model="form.list.menuType" placeholder="请选择类型">
          <a-option :value="1" label="目录" />
          <a-option :value="2" label="路由" />
          <a-option :value="3" label="API" />
          <a-option :value="4" label="路由和API" />
        </a-select>
      </a-form-item>
      <a-form-item
        field="menuName"
        label="名称:"
        :validate-trigger="['change', 'input', 'blur']"
        allow-clear
      >
        <a-input v-model="form.list.menuName" placeholder="请输入名称" />
      </a-form-item>

      <a-form-item field="ownerOs" label="所属端:">
        <a-select v-model="form.list.ownerOs" placeholder="请选择权限所属端">
          <a-option :value="2" label="用户端" />
          <a-option :value="1" label="管理端" />
          <a-option :value="3" label="通用" />
        </a-select>
      </a-form-item>

      <div
        v-if="
          form.list.menuType === 2 ||
          form.list.menuType === 4 ||
          form.list.menuType === 1
        "
      >
        <a-form-item field="parentMenuId" label="上级菜单:" allow-clear>
          <a-cascader
            :field-names="fieldNames"
            :options="GetMenuData"
            v-model="form.list.parentMenuId"
            check-strictly
            :load-more="loadMore"
            placeholder="请选择上层文件夹"
          />
        </a-form-item>
        <!-- 路由相关 -->
        <a-form-item field="path" label="路由路径:">
          <a-input v-model="form.list.path" placeholder="请输入路由路径" />
        </a-form-item>
        <a-form-item field="icon" label="菜单图标:">
          <a-input v-model="form.list.icon" placeholder="请输入菜单icon" />
        </a-form-item>
        <a-form-item field="component" label="路由组件路径:">
          <a-input v-model="form.list.component" placeholder="请输入组件路径" />
        </a-form-item>
        <a-form-item field="visible" label="路由菜单显示:">
          <a-switch
            v-model="form.list.visible"
            :checked-value="1"
            :unchecked-value="2"
          />
        </a-form-item>
        <a-form-item field="isCache" label="路由是否缓存:">
          <a-switch
            v-model="form.list.isCache"
            :checked-value="1"
            :unchecked-value="2"
          />
        </a-form-item>
        <a-form-item field="orderNum" label="显示顺序:">
          <a-input-number
            :min="0"
            v-model="form.list.orderNum"
            placeholder="请输入显示顺序"
          />
        </a-form-item>
        <!-- <a-form-item :width="300" field="meta" label="菜单栏隐藏:">
          <a-switch
            v-model="form.meta"
            :checked-value="`{\&quot;hideMenu\&quot;:true}`"
            :unchecked-value="`{\&quot;hideMenu\&quot;:false}`"
          />
        </a-form-item> -->
        <a-form-item :width="300" field="meta" label="白名单菜单:">
          <a-switch
            v-model="form.list.isWhiteList"
            :checked-value="1"
            :unchecked-value="2"
          />
        </a-form-item>
      </div>
      <div v-if="form.list.menuType === 3 || form.list.menuType === 4">
        <!-- 接口相关 -->
        <a-form-item field="reqUrl" label="请求路径:">
          <a-input v-model="form.list.reqUrl" placeholder="请求路径" />
        </a-form-item>
        <a-form-item field="method" label="请求类型:">
          <a-select v-model="form.list.method" placeholder="请选择类型">
            <a-option value="get" label="get" />
            <a-option value="post" label="post" />
            <a-option value="put" label="put" />
            <a-option value="delete" label="delete" />
          </a-select>
        </a-form-item>
        <a-form-item field="baseUrl" label="baseUrl:">
          <a-select v-model="form.list.baseUrl" placeholder="baseUrl">
            <a-option
              v-for="(item, index) in envList"
              :key="index"
              :value="item"
              :label="item"
            />
          </a-select>
        </a-form-item>
        <a-form-item field="hookId" label="api钩子标识:">
          <a-input v-model="form.list.hookId" placeholder="请求路径" />
        </a-form-item>
        <a-form-item :width="300" field="meta" label="数据级模式:">
          <a-switch
            v-model="form.list.dataLevelMode"
            :checked-value="1"
            :unchecked-value="2"
          />
        </a-form-item>
        <a-form-item :width="300" field="meta" label="权限检测:">
          <a-switch
            v-model="form.list.isEnableAuth"
            :checked-value="true"
            :unchecked-value="false"
          />
        </a-form-item>
      </div>
      <a-form-item :width="300" field="meta" label="数据状态:">
        <a-switch
          v-model="form.list.status"
          :checked-value="1"
          :unchecked-value="2"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import {
  getMenuList,
  postMenuList,
  getMenuParameterDuplicationCheck,
  putMenuList
} from '@/apis/authManagement/index';
import { TMenuAdd } from '@/apis/authManagement/type';
import { cloneDeep } from 'lodash';
// import { TMenuAdd, RevampMenuAdd } from '~/apis/jurisdiction/type';
// import { XPrivilegeList, MenuAdd } from '~/apis/jurisdiction/index';
const emit = defineEmits(['update:visible', 'addMenuModel']);
const getTreeData = ref([]);
const envList: Array<string> = [];
for (const item in import.meta.env) {
  if (item.indexOf('VITE') === 0) {
    envList.push(item);
  }
}
const fieldNames = { value: 'id', label: 'menuName' };
const GetMenuData = ref([
  {
    id: 0,
    baseUrl: '',
    component: '',
    dataLevelMode: 2,
    hookId: '',
    icon: '',
    isCache: undefined,
    isEnableAuth: true,
    isEnableDataLevel: 2,
    isWhiteList: undefined,
    menuName: '主分类',
    menuType: undefined,
    method: '',
    orderNum: undefined,
    ownerOs: undefined,
    parentMenuId: 0,
    path: '',
    props: '',
    remark: '',
    reqUrl: '',
    status: 1,
    visible: 1,
    children: []
  }
]);

const getMenuData = async () => {
  try {
    const res = await getMenuList({ parentMenuId: 0 });
    const modules = import.meta.glob('@/views/Management/**/*');
    GetMenuData.value[0].children = res.menuList;
    // getTreeData.value = res;
  } catch (err: unknown) {
    console.log(err);
  }
};

const props = withDefaults(
  //参数说明
  defineProps<{
    editCompanyForm: any; //修改的数据
    visible: boolean; //是否打开modal
  }>(),
  {
    visible: false
  }
);
// 控制确定取消按钮
const modalVisible = computed({
  //控制visible
  get() {
    return props.visible;
  },
  set() {
    return emit('update:visible', false);
  }
});

const form = reactive<any>({
  list: {
    baseUrl: '', //接口请求域名
    component: '', //组件路径
    dataLevelMode: 2, //数据级模式（1 控件模式 2 列模式）
    hookId: '', //
    icon: '', //菜单图标
    isCache: undefined, //是否缓存（1缓存 2不缓存）
    isEnableAuth: 1, //
    isEnableDataLevel: 2, //是否开启数据级（1 是 2 否）
    isWhiteList: undefined, //是否开启权限检测（1 是 2 否）
    menuName: '', //菜单名称
    menuType: undefined, //菜单类型 1.目录 2.路由 3.api
    method: '', //请求方式
    orderNum: undefined, //显示顺序
    ownerOs: undefined, //所属操作端（1 管理端 2 用户端）
    parentMenuId: 0, //父级菜单id
    path: '', //路由地址
    props: '', //菜单属性
    remark: '', //备注
    reqUrl: '', //接口请求地址
    status: 1, //数据状态(1 启用 2 禁用)
    visible: 1 //菜单显示状态（1显示 2隐藏）
  }
});

const loadMore = (option: any, done: any) => {
  window.setTimeout(async () => {
    const res = await getMenuList({ parentMenuId: option.id });
    await done(res.menuList);
  }, 1000);
};

const rules = {
  menuName: [{ required: true, message: '请输入姓名' }],
  menuType: [{ required: true, message: '请选择类型' }],
  parentMenuId: [{ required: true, message: '请选择上级菜单' }],
  path: [{ required: true, message: '请输入路由路径' }],
  // component: [{ required: true, message: '请输入文件路径' }],
  reqUrl: [{ required: true, message: '请输入请求路径' }],
  method: [{ required: true, message: '请输入请求类型' }],
  baseUrl: [{ required: true, message: '请选择baseUrl' }],
  menuAffiliation: [{ required: true, message: '权限所属端' }]
};

//取消
const closeModal = () => {
  modalVisible.value = false;
};
const formRef = ref();
const visible = ref(false);
const handleSubmit = async () => {
  //提交
  const check = await formRef.value.validate();
  if (!check) {
    try {
      if (!form.list.id) {
        emit('addMenuModel', cloneDeep(form.list), 'add');
      } else if (form.list.id) {
        emit('addMenuModel', cloneDeep(form.list), 'edit');
      }
      closeModal(); // 关闭模态框
      formRef.value.resetFields();
      visible.value = false;
    } catch (err) {
      console.log(err);
    }
  }
  return;
};

onMounted(() => {
  getMenuData();
  if (props.editCompanyForm.id) {
    form.list = props.editCompanyForm;
  }
});
</script>
